Learn Python

Python is a powerful and easy-to-learn programming language. It is widely used in web development, artificial intelligence, data analysis, and many other fields.

Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores(A-z, 0-9, and_)
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords

Example
Legal variable names:
myvar="John"
my_var="John"
_my_var="John"
myVar="John"
MYVAR="John"
myvar2="John"

Example
Illegal variable names:
2myvar="John"
my-var="John"
my var="John"

اضغط لمشاهده الفيديو 👇🏻
The Python print() function is often used to output variables.

Example
x="Python is awesome"
print(x)

In the print() function, you output multiple variables, separated by a comma:

Example
x="Python"
y="is"
z="awesome"
print(x, y, z)

You can also use the+ operator to output multiple variables:

Example
x="Python"
y="is"
z="awesome"
print(x+y+z)

Notice the space character after"Python" and"is", without them the result would be"Pythonisawesome".

For numbers, the+ character works as a mathematical operator:

Example
x=5
y=10
print(x+y)

Python will give you an error:

Example (error)
x=5
y="John"
print(x+y)

شاهد الفيديو التالي هنا👇🏻
Data TypeExample
strx = "Hello World"
intx = 20
floatx = 20.5
complexx = 1j
listx = ["apple", "banana", "cherry"]
tuplex = ("apple", "banana", "cherry")
rangex = range(6)
dictx = {"name" : "John", "age" : 36}
setx = {"apple", "banana", "cherry"}
frozensetx = frozenset({"apple", "banana", "cherry"})
boolx = True
bytesx = b"Hello"
bytearrayx = bytearray(5)
memoryviewx = memoryview(bytes(5))
NoneTypex = None
اضغط لمشاهدة الفيديو 👇🏻
Arithmetic Operators are used to perform mathematical calculations.

OperatorNameExampleResult
+Addition5+38
-Subtraction10-46
*Multiplication3*412
/Division15/35.0
%Modulus10%31
**Exponentiation2**38
//Floor Division17//53

اختبر فهمك:
ما نتيجة 7+3*2؟
Comparison Operators compare two values and return True or False.

OperatorDescriptionExampleResult
==Equal5==5True
!=Not Equal3!=4True
>Greater Than7>10False
<Less Than2<5True
>=Greater or Equal5>=5True
<=Less or Equal3<=2False

اختبر فهمك:
ما نتيجة 10!=10؟
Logical Operators combine conditional statements.

OperatorDescriptionExample
andReturns True if both statements are true5>3 and 2<4 → True
orReturns True if one of the statements is true5>10 or 2<4 → True
notReverse the resultnot(5>10) → True

اختبر فهمك:
ما نتيجة True and False؟
Identity Operators compare objects(memory location), not values.

OperatorDescriptionExample
isReturns True if both variables are the same objectx=[1,2]; y=x; x is y → True
is notReturns True if both variables are different objectsx=[1,2]; y=[1,2]; x is not y → True

ملاحظة: لا تخلط بين ==(المساواة) و is(هوية الكائن)!

اختبر فهمك:
إذا كان a=[1,2] و b=[1,2]، ما نتيجة a is b؟
Assignment Operators assign values to variables.

OperatorExampleSame AsEffect
=x=5-Assign 5 to x
+=x+=3x=x+3Add then assign
-=x-=2x=x-2Subtract then assign
*=x*=4x=x*4Multiply then assign
/=x/=2x=x/2Divide then assign
%=x%=3x=x%3Modulus then assign

اختبر فهمك:
إذا كان num=10 ثم طبقنا num*=2، كم تصبح قيمة num؟
Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code.

Example
if 5>2:
    print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Example
Syntax Error:
if 5>2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one.

You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:

Example
Syntax Error:
if 5>2:
    print("Five is greater than two!")
print("Five is greater than two!")

اضغط لمشاهدة الفيديو هنا 👇🏻
Python supports the usual logical conditions from mathematics:

• Equals: a==b
• Not Equals: a!=b
• Less than: a• Less than or equal to: a<=b
• Greater than: a>b
• Greater than or equal to: a>=b

These conditions can be used in several ways, most commonly in"if statements" and loops.
An"if statement" is written by using the if keyword.

Elif
The elif keyword is Python's way of saying"if the previous conditions were not true, then try this condition".
Example
a=33
b=33
if b>a:
    print("b is greater than a")
elif a==b:
    print("a and b are equal")

Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a=200
b=33
if b>a:
    print("b is greater than a")
elif a==b:
    print("a and b are equal")
else:
    print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that"a is greater than b".
You can also have an else without the elif:
Example
a=200
b=33
if b>a:
    print("b is greater than a")
else:
    print("b is not greater than a")

Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
if a>b: print("a is greater than b")

Short Hand If... Else
If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:
Example
One line if else statement:
a=2
b=330
print("A") if a>b else print("B")

And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a=200
b=33
c=500
if a>b and c>a:
    print("Both conditions are True")

Or
The or keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, OR if a is greater than c:
a=200
b=33
c=500
if a>b or a>c:
    print("At least one of the conditions is True")

Not
The not keyword is a logical operator, and is used to reverse the result of the conditional statement:
Example
Test if a is NOT greater than b:
a=33
b=200
if not a>b:
    print("a is NOT greater than b")

Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x=41
if x>10:
    print("Above ten,")
    if x>20:
        print("and also above 20!")
    else:
        print("but not above 20.")

The pass Statement
if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
Example
a=33
b=200
if b>a:
    pass

شاهد الفيديو لتعلم المزيد 👇🏻
A for loop is used for iterating over a sequence(that is either a list, a tuple, a dictionary, a set, or a string).

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example
Print each fruit in a fruit list:
fruits=["apple","banana","cherry"]
for x in fruits:
print(x)

👉🏻شاهد الفيديو على YouTube
With >the break statement we can stop the loop before it has looped through all the items:

1 Example
Exit the loop when x is"banana":
fruits=["apple","banana","cherry"]
for x in fruits:
print(x)
if x=="banana":
break

2 Example
Exit the loop when x is "banana", but this time the break comes before the print:
fruits=["apple","banana","cherry"]
for x in fruits:
if x=="banana":
break
print(x)
With the continue statement we can stop the current iteration of the loop, and continue with the next:

Example
Do not print banana:
fruits=["apple","banana","cherry"]
for x in fruits:
if x=="banana":
continue
print(x)
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
With the while loop we can execute a set of statements as long as a condition is true.

Example
Print i as long as i is less than 6:
i=1
while i<6:
    print(i)
    i+=1

شاهد الفيديو على YouTube
With the break statement we can stop the loop even if the while condition is true:

Example
Exit the loop when i is 3:
i=1
while i<6:
    print(i)
    if i==3:
        break
    i+=1
With the continue statement we can stop the current iteration, and continue with the next:

Example
Continue to the next iteration if i is 3:
i=0
while i<6:
    i+=1
    if i==3:
        continue
    print(i)
With the else statement we can run a block of code once when the condition no longer is true:

Example
Print a message once the condition is false:
i=1
while i<6:
    print(i)
    i+=1
else:
    print("i is no longer less than 6")

Lists are used to store multiple items in a single variable.

شاهد الفيديو لتعلم المزيد👇🏻

There are several methods to add items to a list in Python. The most common methods are append() and insert().

append() - Adds an element to the end of the list.

Syntax:
list.append(element)

Example:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
Output: ["apple", "banana", "cherry", "orange"]
insert() - Adds an element at a specified position.

Syntax:
list.insert(index, element)

Example:
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange")
print(fruits)
Output: ["apple", "orange", "banana", "cherry"]
extend() - Adds all elements from an iterable to the end of the list.

Syntax:
list.extend(iterable)

Example:
fruits = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
fruits.extend(tropical)
print(fruits)
Output: ["apple", "banana", "cherry", "mango", "pineapple", "papaya"]

There are several methods to remove items from a list in Python.

remove() - Removes the first occurrence of a specified value.

Syntax:
list.remove(value)

Example:
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
Output: ["apple", "cherry"]
pop() - Removes and returns the element at the specified index.

Syntax:
list.pop(index)

Example:
fruits = ["apple", "banana", "cherry"]
fruits.pop(1)
print(fruits)
Output: ["apple", "cherry"]
clear() - Removes all elements from the list.

Syntax:
list.clear()

Example:
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)
Output: []

Python lists have a built-in sort() method that modifies the list in-place.

sort() - Sorts the list in ascending order by default.

Syntax:
list.sort()

Example:
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits)
Output: ["apple", "banana", "cherry"]
Use the reverse=True parameter to sort in descending order.

Syntax:
list.sort(reverse=True)

Example:
numbers = [100, 50, 65, 82, 23]
numbers.sort(reverse=True)
print(numbers)
Output: [100, 82, 65, 50, 23]
Complete List of Python List Methods:

MethodDescription
append()Adds an element to the end
clear()Removes all elements
copy()Returns a copy of the list
count()Returns count of an element
extend()Adds elements from an iterable
index()Returns index of first occurrence
insert()Adds element at specified position
pop()Removes and returns element at index
remove()Removes first occurrence of value
reverse()Reverses the list order
sort()Sorts the list